package controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.SysRole;
import pojo.SysUser;
import service.SysRoleService;
import service.SysUserService;
import utils.Constants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RequestMapping("/sysUser")
@Controller
//@RestController
public class SysUserController extends BaseController {
    @Resource
    SysUserService sysUserService;
    @Resource
    SysRoleService sysRoleService;

    /**
     * 模拟异常
     * @return
     */
    @RequestMapping("/exLogin")
    public String exLogin(String account, String password){
        SysUser sysUser = sysUserService.login(account, password);
        if(sysUser==null){
            throw  new RuntimeException("用户名或者密码错误");
        }
        return "redirect:/sysUser/toMain";
    }

   /* *//**
     * 只捕获当前controller中方法的发生异常
     * @param model
     * @return
     *//*
    @ExceptionHandler(value = {RuntimeException.class})
    public String hander(Model model,RuntimeException exception){
        //1.将错误信息保存到model
        model.addAttribute("e",exception);
        //2.转发到错误页面
        return "sysError";
    }*/
    @RequestMapping("/list")
    public String list(String queryRealName,Integer queryRoleId,
                       @RequestParam(defaultValue = "1") Integer pageIndex,
                       Model model){
        //设置每页显示条数
        int pageSize=5;
        //查询总共多少条记录
        int totalCount=sysUserService.selectCount(queryRealName,queryRoleId);
        //计算总页数
        int totalPageCount=0;
        if(totalCount%pageSize==0){
            totalPageCount=totalCount/pageSize;
        }else{
            totalPageCount=totalCount/pageSize+1;
        }

        //分页极端处理 ;这个东西一定要在查询分页数据之前做，在计算总页数之后做
        if(pageIndex>totalPageCount){
            pageIndex=totalPageCount;
        }
        if(pageIndex<1){
            pageIndex=1;
        }

        //查询每页显示的数据
        List<SysUser> userList = sysUserService.selectList(queryRealName, queryRoleId, pageIndex, pageSize);

        model.addAttribute("currentPageNo",pageIndex);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("userList",userList);


        //查询所有的角色用户角色下拉框的展示
        List<SysRole> roleList = sysRoleService.selectList();
        model.addAttribute("roleList",roleList);

        //回显查询条件
        model.addAttribute("queryRealName",queryRealName);
        model.addAttribute("queryRoleId",queryRoleId);



        return "sysUser/list";
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "sysUser/add";
    }

    @RequestMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest request,HttpSession session, MultipartFile idPic, MultipartFile workPic){
        System.out.println("add方法执行了");
        if(idPic!=null && !idPic.isEmpty()) {
            //1.对文件进行重命名
            //获取上传文件旧的文件名
            String oldFileName = idPic.getOriginalFilename();//1.jpg 1.png
            //获取文件名后缀
            String suffix = FilenameUtils.getExtension(oldFileName);
            //文件名的格式规则：当前系统时间+随机数+"_Personal."+文件后缀
            String newFileName = System.currentTimeMillis() +
                    RandomUtils.nextInt(1000000) +
                    "_Personal." +
                    suffix;
            System.out.println("newFileName:" + newFileName);
            //2.上传文件
            String path = "/statics/upload/";
            String realPath = request.getServletContext().getRealPath(path);
            System.out.println("realPath:" + realPath);
            //判断文件夹是否存在
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                idPic.transferTo(new File(realPath, newFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.将文件上传的路劲存储到数据库
            sysUser.setIdPicPath(path + newFileName);
        }
        if(workPic!=null && !idPic.isEmpty()) {
            //1.对文件进行重命名
            //获取上传文件旧的文件名
            String oldFileName = workPic.getOriginalFilename();//1.jpg 1.png
            //获取文件名后缀
            String suffix = FilenameUtils.getExtension(oldFileName);
            //文件名的格式规则：当前系统时间+随机数+"_Personal."+文件后缀
            String newFileName = System.currentTimeMillis() +
                    RandomUtils.nextInt(1000000) +
                    "_Personal." +
                    suffix;
            System.out.println("newFileName:" + newFileName);
            //2.上传文件
            String path = "/statics/upload/";
            String realPath = request.getServletContext().getRealPath(path);
            System.out.println("realPath:" + realPath);
            //判断文件夹是否存在
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                workPic.transferTo(new File(realPath, newFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.将文件上传的路劲存储到数据库
            sysUser.setWorkPicPath(path + newFileName);
        }

        //设置创建人的id
        SysUser user=(SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreatedUserId(user.getId());

        //将页面传过来的数据保存到数据库
        int rs=sysUserService.insert(sysUser);
        if(rs>0){
            //跳转到用户列表
            return "redirect:/sysUser/list";
        }else{
            //返回到新增页面
            return "sysUser/add";
        }
    }

    /**
     * 要修改数据回显
     * @param id
     * @return
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam("uid") Integer id,Model model){
        SysUser sysUser=sysUserService.selectById(id);
        //将数据传入页面
        model.addAttribute("sysUser",sysUser);
        //返回页面
        return "sysUser/update";
    }

    @RequestMapping("/update")
    public String update(SysUser sysUser,HttpSession session,HttpServletRequest request,
                         MultipartFile idPic,MultipartFile workPic){
        if(idPic!=null && !idPic.isEmpty()) {
            //1.对文件进行重命名
            //获取上传文件旧的文件名
            String oldFileName = idPic.getOriginalFilename();//1.jpg 1.png
            //获取文件名后缀
            String suffix = FilenameUtils.getExtension(oldFileName);
            //文件名的格式规则：当前系统时间+随机数+"_Personal."+文件后缀
            String newFileName = System.currentTimeMillis() +
                    RandomUtils.nextInt(1000000) +
                    "_Personal." +
                    suffix;
            System.out.println("newFileName:" + newFileName);
            //2.上传文件
            String path = "/statics/upload/";
            String realPath = request.getServletContext().getRealPath(path);
            System.out.println("realPath:" + realPath);
            //判断文件夹是否存在
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                idPic.transferTo(new File(realPath, newFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.将文件上传的路劲存储到数据库
            sysUser.setIdPicPath(path + newFileName);
        }

        if(workPic!=null && !workPic.isEmpty()) {
            //1.对文件进行重命名
            //获取上传文件旧的文件名
            String oldFileName = workPic.getOriginalFilename();//1.jpg 1.png
            //获取文件名后缀
            String suffix = FilenameUtils.getExtension(oldFileName);
            //文件名的格式规则：当前系统时间+随机数+"_Personal."+文件后缀
            String newFileName = System.currentTimeMillis() +
                    RandomUtils.nextInt(1000000) +
                    "_Personal." +
                    suffix;
            System.out.println("newFileName:" + newFileName);
            //2.上传文件
            String path = "/statics/upload/";
            String realPath = request.getServletContext().getRealPath(path);
            System.out.println("realPath:" + realPath);
            //判断文件夹是否存在
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                workPic.transferTo(new File(realPath, newFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.将文件上传的路劲存储到数据库
            sysUser.setWorkPicPath(path + newFileName);
        }

        //获取当前登录用户
        SysUser user=(SysUser) session.getAttribute(Constants.USER_SESSION);
        //设置修改人的id
        sysUser.setUpdatedUserId(user.getId());

        int rs=sysUserService.update(sysUser);

        if(rs>0){
            //跳转到列表
            return "redirect:/sysUser/list";
        }else{
            //跳转到修改页面
            return "redirect:/sysUser/toUpdate";
        }

    }

   /* @RequestMapping("/view")
    public String view(Integer id,Model model){
        SysUser sysUser=sysUserService.selectById(id);
        //将数据传入页面
        model.addAttribute("sysUser",sysUser);
        //返回页面
        return "sysUser/view";
    }*/

    @RequestMapping("/view/{uid}")
    //view?id=34
    //view/34
    //@PathVariable和@RequestParam
    public String view(@PathVariable("uid") Integer id, Model model){
        SysUser sysUser=sysUserService.selectById(id);
        //将数据传入页面
        model.addAttribute("sysUser",sysUser);
        //返回页面
        return "sysUser/view";
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping(value = "/addSpring",method = RequestMethod.GET)
    public String toAddSpring(@ModelAttribute SysUser sysUser){
        return "sysUser/add-spring";
    }

    @RequestMapping(value = "/addSpring",method =RequestMethod.POST )
    public String addSpring(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session,Model model){
        //判断是否验证失败
        if(bindingResult.hasErrors()){
          /*  if(bindingResult.hasFieldErrors("account")){
                model.addAttribute("account",bindingResult.getFieldError("account"))
            }*/
            return "sysUser/add-spring";
        }

        //设置创建人的id
        SysUser user=(SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreatedUserId(user.getId());

        //将页面传过来的数据保存到数据库
        int rs=sysUserService.insert(sysUser);
        if(rs>0){
            //跳转到用户列表
            return "redirect:/sysUser/list";
        }else{
            //返回到新增页面
            return "sysUser/add-spring";
        }
    }

    @RequestMapping("/userExist")
    @ResponseBody
   //1.将方法的返回值转换成json格式的字符串 并将其响应给浏览器
    public Object userExist(String account)  {
        Map<String,Object> map=new HashMap<>();

        SysUser sysUser = sysUserService.selectAccount(account);
        if(sysUser!=null){
            map.put("exist",1);
        }else{
            map.put("exist",0);
        }

        return map;
    }

    @RequestMapping(value = "/delete/{uid}",method = RequestMethod.DELETE)
    @ResponseBody
    public Object delete(@PathVariable("uid") int id){
        Map<String,Object> map=new HashMap<>();

        int i = sysUserService.delete(id);
        if(i>0){
            map.put("delResult","true");
        }else{
            map.put("delResult","false");
        }

        return map;
    }

    @RequestMapping("/{uid}/view")
    @ResponseBody
    public Object view(@PathVariable("uid") Integer id){
        return sysUserService.selectById(id);
    }
}
